package com.example.inami.third.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.example.inami.third.entity.*;
import com.example.inami.third.entity.param.NbIotYunDeviceInfoParam;
import com.example.inami.third.service.NbIotYunSyncInfoService;
import com.example.inami.util.RestTemplateUtil;
import com.example.inami.common.domain.R;
import com.example.inami.common.web.BaseController;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.inami.third.service.NbIotYunDeviceInfoService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备信息表(NbIotYunDeviceInfo)表控制层
 *
 * @author inami
 * @since 2025-02-28 14:47:46
 */
@RestController
@RequestMapping("nbIotYunDeviceInfo")
public class NbIotYunDeviceInfoController extends BaseController {

    private static final String DEVICE_LIST_URL = "https://webapi.nbiotyun.com/api/v1/dev/getList";
    private static final String DEVICE_INFO_URL = "https://webapi.nbiotyun.com/api/v1/dev/get";

    /**
     * 服务对象
     */
    @Resource
    private NbIotYunDeviceInfoService nbIotYunDeviceInfoService;
    @Resource
    private NbIotYunSyncInfoService nbIotYunSyncInfoService;

    /**
     * 分页查询所有数据
     *
     * @param page               分页对象
     * @param nbIotYunDeviceInfo 查询实体
     * @return 所有数据
     */
    @RequestMapping("list")
    public R selectAll(Page<NbIotYunDeviceInfo> page, NbIotYunDeviceInfo nbIotYunDeviceInfo) {
        return R.ok(this.nbIotYunDeviceInfoService.page(page, new QueryWrapper<>(nbIotYunDeviceInfo)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @RequestMapping("{id}")
    public R selectOne(@PathVariable Serializable id) {
        return R.ok(this.nbIotYunDeviceInfoService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param nbIotYunDeviceInfo 实体对象
     * @return 新增结果
     */
    @RequestMapping("save")
    public R insert(@RequestBody @Validated NbIotYunDeviceInfo nbIotYunDeviceInfo) {
        return R.ok(this.nbIotYunDeviceInfoService.save(nbIotYunDeviceInfo));
    }

    /**
     * 修改数据
     *
     * @param nbIotYunDeviceInfo 实体对象
     * @return 修改结果
     */
    @RequestMapping("update")
    public R update(@RequestBody NbIotYunDeviceInfo nbIotYunDeviceInfo) {
        return R.ok(this.nbIotYunDeviceInfoService.updateById(nbIotYunDeviceInfo));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @RequestMapping("delete")
    public R delete(@RequestParam("idList") List<Long> idList) {
        return R.ok(this.nbIotYunDeviceInfoService.removeByIds(idList));
    }

    @RequestMapping("/getDeviceList")
    @ResponseBody
    @Transactional
    public String getDeviceList(@RequestBody(required = false) PageParam param) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("appKey", "j7RYj52A");
        long l = System.currentTimeMillis();
        String currentTime = String.valueOf(l);
        headers.set("timestamp", currentTime);
        String signature = "/api/v1/dev/getList"+currentTime+"ebdd4323ff832807db49ef311eccce4b717e2c03";
        String encryptedSignature = md5(signature);
        headers.set("signature", encryptedSignature);
        // 调用第三方平台接口
        Integer pageSize = param.getPageSize();
        if (pageSize == null) {
            pageSize = 100;
            param.setPageSize(pageSize);
        }
        Integer pageNum = param.getPageNum();
        if (pageNum == null) {
            pageNum = 1;
            param.setPageNum(pageNum);
        }
        Integer fullFlag = param.getFullFlag();
        if (fullFlag == null) {
            fullFlag = 1;
            param.setFullFlag(fullFlag);
        }
        JSONObject jsonObject = RestTemplateUtil.post(headers, DEVICE_LIST_URL, JSONObject.toJSONString(param));
        //String json =  "{\"code\":\"OK\",\"success\":true,\"message\":{\"data\":[{\"deviceId\":148895546,\"deviceTypeName\":\"烟雾报警器\",\"registerSign\":1,\"state\":7,\"deviceModelName\":\"SN-828\",\"createTime\":\"2025-02-27 14:27:22\",\"updateTime\":\"2025-02-27 14:28:16.044\",\"deviceImei\":\"861137062158116\",\"companyName\":\"王平镇\"},{\"deviceId\":148895545,\"deviceTypeName\":\"烟雾报警器\",\"registerSign\":1,\"state\":0,\"deviceModelName\":\"SN-828\",\"createTime\":\"2025-02-27 14:27:21\",\"updateTime\":\"2025-02-28 13:12:13.082\",\"deviceImei\":\"861137062176969\",\"companyName\":\"大峪街道\"},{\"deviceId\":148217962,\"deviceTypeName\":\"烟雾报警器\",\"registerSign\":1,\"state\":2,\"latitude\":\"39.977801\",\"longitude\":\"116.093363\",\"deviceModelName\":\"SN-828\",\"roomName\":\"北厂64号\",\"installAddress\":\"北京市北京市门头沟区琉璃渠后街\",\"createTime\":\"2024-11-12 17:19:21\",\"updateTime\":\"2025-02-28 10:12:04.458\",\"deviceImei\":\"861137062745284\",\"iccid\":\"89861124203029445194\",\"contact\":\"李东升\",\"phonenumber\":\"15313312282\",\"region\":\"北京市-北京市-门头沟区-龙泉地区-琉璃渠村委会\",\"companyName\":\"个人13717783825\"},{\"deviceId\":148217963,\"deviceTypeName\":\"烟雾报警器\",\"registerSign\":1,\"state\":7,\"deviceModelName\":\"SN-828\",\"createTime\":\"2024-11-12 17:19:21\",\"updateTime\":\"2024-11-13 10:11:49.567\",\"deviceImei\":\"861137062761372\",\"companyName\":\"龙泉镇\"},{\"deviceId\":148217961,\"deviceTypeName\":\"烟雾报警器\",\"registerSign\":1,\"state\":2,\"latitude\":\"39.976754\",\"longitude\":\"116.095641\",\"deviceModelName\":\"SN-828\",\"roomName\":\"琉璃渠后街104\",\"installAddress\":\"北京市北京市门头沟区\",\"createTime\":\"2024-11-12 17:19:20\",\"updateTime\":\"2025-02-28 09:22:52.117\",\"deviceImei\":\"861137064241340\",\"iccid\":\"89861124203029443876\",\"contact\":\"15611507221\",\"phonenumber\":\"15611507221\",\"region\":\"北京市-北京市-门头沟区-龙泉地区-琉璃渠村委会\",\"companyName\":\"个人15611507221\"}],\"pageSize\":5,\"pageCount\":1019,\"currentPage\":1,\"total\":5094}}\n";
        //System.out.println(json);
        //JSONObject jsonObject = JSON.parseObject(json);
        JSONObject message = jsonObject.getJSONObject("message");
        JSONArray jsonArray = message.getJSONArray("data");
        List<NbIotYunDeviceInfo> deviceInfoList = jsonArray.toJavaList(NbIotYunDeviceInfo.class);
        NbIotYunSyncInfo syncInfo = new NbIotYunSyncInfo();
        long id = IdWorker.getId();
        syncInfo.setId(id);
        syncInfo.setSyncTime(new Date());
        syncInfo.setPageNum(pageNum);
        syncInfo.setPageSize(pageSize);
        syncInfo.setSyncInfo(jsonObject.toJSONString());
        syncInfo.setOtherParam(param.toString());
        nbIotYunSyncInfoService.save(syncInfo);
        for (NbIotYunDeviceInfo nbIotYunDeviceInfo : deviceInfoList) {
            nbIotYunDeviceInfo.setSyncId(syncInfo.getId());
        }
        boolean b = nbIotYunDeviceInfoService.saveOrUpdateBatch(deviceInfoList, 100);

        return "ok";
    }

    @RequestMapping("/getDeviceInfo")
    @ResponseBody
    @Transactional
    public String getDeviceInfo(String deviceImei,String fullFlag) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("appKey", "j7RYj52A");
        long l = System.currentTimeMillis();
        String currentTime = String.valueOf(l);
        headers.set("timestamp", currentTime);
        String signature = "/api/v1/dev/get"+currentTime+"ebdd4323ff832807db49ef311eccce4b717e2c03";
        String encryptedSignature = md5(signature);
        headers.set("signature", encryptedSignature);
        // 调用第三方平台接口
        Map<String,String> map = new HashMap<>();
        map.put("deviceImei", deviceImei);
        map.put("fullFlag", fullFlag);
        JSONObject jsonObject = RestTemplateUtil.post(headers, DEVICE_INFO_URL, JSONObject.toJSONString(map));
        JSONObject message = jsonObject.getJSONObject("message");
        NbIotYunDeviceInfo nbIotYunDeviceInfo = message.toJavaObject(NbIotYunDeviceInfo.class);
        nbIotYunDeviceInfoService.saveOrUpdate(nbIotYunDeviceInfo);
        return "ok";
    }

    // MD5加密方法
    public static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }


}

